import BackgroundEditer from "@/game/view/BackgroundEditerView";
import BaseController from "../BaseController";
import { ControlEvent, ViewEvent } from "@/const";
import LayerModel from "@/game/model/LayerModel";
import ApiHelper from "@/api/ApiHelper";
import cjs=createjs

export default class EditController extends BaseController {
    //编辑器视图
    private _view:BackgroundEditer;
    //图层实体
    private _layers:LayerModel[];
    start(): void {
        //编辑器视图
        this._view=new BackgroundEditer();
        this.layer.game_layer.addChild(this._view);

        this.message.once(ControlEvent.SHOW_EDITOR,()=>{
            //显示编辑器
            ApiHelper.getInstance().getGameConfig(this.option.id).then(res=>{
                console.log(res)
                //const layers=res.layer
                this._layers=res.layer.map(item=>LayerModel.create(item))//LayerModel.create(res.layer)
                this._view.init(this._layers)
            }).catch(err=>{
                console.log(err)
            })
        })
        //
        this.message.on(ViewEvent.ADD_IMAGE,(e:any)=>{
            //添加图片
            console.log(e.data)
            const parentName=e.data.parentName
            for(let i=0;i<this._layers.length;i++){
                const model=this._layers[i]
                if(model.name==parentName){
                    model.children.push(e.data.model)
                    break
                }
            }
            this._view.init(this._layers)
        })
        //
        this.message.on(ViewEvent.FLUSH_EDITER,()=>{
            //刷新编辑器
            console.log(this._layers)
        })
        this.message.on(ViewEvent.SAVE_GAME,()=>{
            //保存游戏
            ApiHelper.getInstance().saveGame(this.option.id,JSON.stringify({layer:this._layers})).then(res=>{
                console.log(res)
            }).catch(err=>{
                console.log(err)
            })
        })
    }
}